package 
{
	import app.AppSettings;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
		import flash.events.ContextMenuEvent;
		import gui.LoaderIndicator;
		import gui.PositionInfo;
		import utils.CustomContextMenu;
		import utils.DebugWindow;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class Preloader extends MovieClip 
	{
		private var _preloader:LoaderIndicator;
		
		public function Preloader() 
		{
			if (stage) 
			{
				stage.scaleMode = StageScaleMode.NO_SCALE;
				//stage.align = StageAlign.TOP_LEFT;
			}
			CustomContextMenu.getInstance().createMyMenu(this, DebugWindow, this);
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			// TODO show loader
			var pos:PositionInfo = new PositionInfo();
			pos.align = PositionInfo.ALIGN_CENTR_X;
			pos.addAlign(PositionInfo.ALIGN_CENTR_Y);
			var loaderRadius:Number = 25;
			_preloader = new LoaderIndicator(loaderRadius, 15);
			_preloader.x = pos.getPosX(AppSettings.APP_WIDTH, loaderRadius * 2);
			_preloader.y = pos.getPosY(AppSettings.APP_HEIGHT, loaderRadius * 2);
			addChild(_preloader);
		}
		
		
		
		
		private function ioError(e:IOErrorEvent):void 
		{
			trace(e.text);
		}
		
		private function progress(e:ProgressEvent):void 
		{
			// TODO update loader
		}
		
		private function checkFrame(e:Event):void 
		{
			if (currentFrame == totalFrames) 
			{
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void 
		{
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			// TODO hide loader
			if (_preloader != null && _preloader.parent != null)
			{
				_preloader.parent.removeChild(_preloader);
			}
			startup();
		}
		
		private function startup():void 
		{
			var mainClass:Class = getDefinitionByName("Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
		
	}
	
}